package com.chujian.framework.web.interceptor;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.chujian.framework.auth.AccessorHolder;
import com.chujian.framework.auth.DynamicAuth;
import com.chujian.framework.auth.SecurityConst;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ：chujian
 * @since ：2021-8-12
 * 功能动态信息解析拦截器
 */
@Slf4j
public class FuncDynamicHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String funcInfoHeader = request.getHeader(SecurityConst.FUNC_DYNAMIC_INFO_HEADER);
        if (null != AccessorHolder.getAccessor() && StringUtils.isNotEmpty(funcInfoHeader)) {

            try {
                String funcInfo = Base64.decodeStr(funcInfoHeader);

                DynamicAuth dynamicAuth = JSON.parseObject(funcInfo, DynamicAuth.class);

                // 设置请求相关信息
                String url = request.getHeader(SecurityConst.REAL_REQUEST_URL_HEADER);
                String method = request.getMethod().toLowerCase();
                dynamicAuth.setRequestUrl(url).setRequestMethod(method);

                AccessorHolder.getAccessor().setDynamicAuth(dynamicAuth);
            } catch (Exception e) {
                log.error("功能动态信息解析失败", e);
            }
        }
        return true;
    }
}
